'use strict';

const { Service } = require('egg');
const ModelName = 'GiftSend'
class RouterService extends Service {
  /**
   * 根据分页和搜索条件获取
   * @param {Object} where 查询用户的条件
   * @param {Number} page 当前分页
   * @param {Number} pageSize 当前页每页多少条
   */
  async getPage(where, page, pageSize) {
    return this.ctx.model[ModelName].findAndCountAll({
      where,
      offset: pageSize * (page - 1),
      limit: pageSize,
      order:[
        // id 降序
        ['create_time','ASC']
      ],
      include: [{ model: this.ctx.model.Gift }]
    });
  }

  // 所有列表
  async allList() {
    return this.ctx.model[ModelName].findAll({
      order:[
        // id 降序
        ['create_time','ASC']
      ],
    });
  }
  async findOne(id) {
    return this.ctx.model[ModelName].findOne({
      where: {
        id,
      },
      include: [{ model: this.ctx.model.Gift }]
    });
  }

  /**
   * 创建
   * @param {*} data 角色信息
   */
  async create(data) {
    const res = await this.ctx.model[ModelName].create(data)
    for (let i = 0; i < data.memberIdList.length; i++) {
        // 生成礼品码 6位 规则 英文数字, 每三位中间横杠
        let code = Math.random().toString(36).substr(2, 6).toUpperCase();
        code = code.replace(/(.{3})/g, '$1-').slice(0, -1);
        // 用户id + 礼品 id + 礼品码
        code = `${data.memberIdList[i]}-${data.gift_id}-${code}`
        await this.ctx.model.GiftSendItem.create({
            ...data,
            gift_send_id: res.id,
            member_id: data.memberIdList[i],
            code
        })
    }
    return res;
  }

  /**
   * 根据ID修改
   * @param {Number} id ID
   * @param {Object} data 要修改的信息
   */
  async update(id, data) {
    return await this.ctx.model[ModelName].update(data, { where: { id } });
  }

  /**
   * 根据id删除
   * @param {Number}
   */
  async deleteById(id) {
    return await this.ctx.model[ModelName].destroy({ where: { id } });
  }
}

module.exports = RouterService;
